package com.verisette.ncos.web.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.verisette.ncos.common.MailConstant;
import com.verisette.ncos.common.ProjectConstant;
import com.verisette.ncos.persistence.domain.MasterMember;
import com.verisette.ncos.persistence.domain.MasterUserProfile;
import com.verisette.ncos.persistence.domain.TransCustomerOrder;

public class SendNotifyMailThread extends Thread {
	Logger logger = Logger.getLogger(SendNotifyMailThread.class);
	private String mailTemplate;
	private MasterUserProfile sender;
	private MasterUserProfile receiver;
	private String emailToReceivers;//delimitor ','
	private String emailCcReceivers;//delimitor ','
	private TransCustomerOrder order;
	private List<String> contentParams;
	private String subjectContent;
	
	private List<File> attachments;
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		MasterMember member = order.getMasterMember();
		
		if(logger.isDebugEnabled()) {
			logger.debug("###### SMTP_USER : " + MailConstant.SMTP_USER);
			logger.debug("###### SMTP_PASSWORD : " + MailConstant.SMTP_PASSWORD);
		}
		
		Session session = Session.getInstance(MailConstant.SMTP_PROPS,
				  new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(MailConstant.SMTP_USER, MailConstant.SMTP_PASSWORD);
					}
				  });
		
		try {
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(MailConstant.SMTP_USER));
			if(logger.isDebugEnabled()) logger.debug("\n\t\treceiver email-list : " + this.emailToReceivers);
			if(StringUtils.isBlank(this.emailToReceivers)){
				this.emailToReceivers = receiver.getUspEmail();
			}
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(emailToReceivers));
			if(logger.isDebugEnabled()) logger.debug("\n\t\treceiver email-list cc: " + this.emailCcReceivers);
			if(StringUtils.isNotBlank(this.emailCcReceivers)){
				message.setRecipients(Message.RecipientType.CC,
						InternetAddress.parse(emailCcReceivers));
			}
			String requesterName = member.getMmbFnameTh(), requesterLname = member.getMmbLnameTh();
			if( StringUtils.isBlank(requesterName)){
				requesterName = member.getMmbFnameEn();
				requesterLname = member.getMmbLnameEn();
			}
			
			StringBuilder subjSb = new StringBuilder("ระบบนามบัตรออนไลน์ : นามบัตรของคุณ %s %s ");
			if(subjectContent!=null && subjectContent.length()>0){
				subjSb.append(subjectContent);
			}else{
				subjSb.append("รออนุมัติ");
			}
			
			message.setSubject(String.format(subjSb.toString(), requesterName, requesterLname), "UTF-8");
			//Old
//			message.setContent(
//					String.format(MailConstant.mailTemplateMap.get(this.mailTemplate),
//							contentParams.toArray()), 
//					"text/html;charset=UTF-8;");

			//New
			Multipart mp = new MimeMultipart();
			
			MimeBodyPart mb1 = new MimeBodyPart();
			mb1.setContent(
					String.format(MailConstant.mailTemplateMap.get(this.mailTemplate),
							contentParams.toArray()), 
					"text/html;charset=UTF-8;");
			mp.addBodyPart(mb1);
			
			if(this.attachments!=null){
				MimeBodyPart mbFile = null;
				for(File f : this.attachments){
					try{
						mbFile = new MimeBodyPart();
						mbFile.attachFile(f);
						
						mp.addBodyPart(mbFile);
					}catch(Exception ex){
						logger.error("Attachements failed.", ex);
					}
				}
			}
			
			message.setContent(mp);

			if(logger.isDebugEnabled()) {
				StringBuilder sb = new StringBuilder();
				javax.mail.Address[] addrs = message.getRecipients(Message.RecipientType.TO);
				for(javax.mail.Address a : addrs){
					sb.append(",").append(a);
				}
				sb.deleteCharAt(0);
				logger.debug("###### Recipients : \n\t\t" + sb);
			}
			
			Transport.send(message);
			
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
	public void setMailTemplate(String mailTemplate) {
		this.mailTemplate = mailTemplate;
	}
	public void setOrder(TransCustomerOrder order) {
		this.order = order;
	}
	public void setSender(MasterUserProfile sender) {
		this.sender = sender;
	}
	public void setReceiver(MasterUserProfile receiver) {
		this.receiver = receiver;
	}
	public void addEmailToReceivers(String receiver){
		StringBuilder sbf = new StringBuilder();
		if(StringUtils.isBlank(this.emailToReceivers)){
			sbf.append(receiver);
		} else {
			sbf.append(this.emailToReceivers);
			sbf.append(",").append(receiver);
		}
		this.emailToReceivers=sbf.toString();
	}
	public void addEmailCcReceivers(String receiver){
		StringBuilder sbf = new StringBuilder();
		if(StringUtils.isBlank(this.emailCcReceivers)){
			sbf.append(receiver);
		} else {
			sbf.append(this.emailCcReceivers);
			sbf.append(",").append(receiver);
		}
		this.emailCcReceivers=sbf.toString();
	}
	public void addContentParam(String s){
		if(this.contentParams==null) this.contentParams=new ArrayList<String>();
		this.contentParams.add(s);
	}
	public void addAttachment(File file){
		if(this.attachments==null){
			this.attachments=new ArrayList<File>();
		}
		attachments.add(file);
	}
	public void setSubjectContent(String subjectContent) {
		this.subjectContent = subjectContent;
	}
	
	public static void main(String[] args) throws Exception {

		Session session = Session.getInstance(MailConstant.SMTP_PROPS,
				  new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(MailConstant.SMTP_USER, MailConstant.SMTP_PASSWORD);
					}
				  });
		
		try {
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(MailConstant.SMTP_USER));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse("wtrakuldon@gmail.com"));
			message.setRecipients(Message.RecipientType.CC, 
					InternetAddress.parse("w_trakuldon@hotmail.com"));
			message.setSubject("หยังนิ", "UTF-8");
			
			MimeBodyPart mb1 = new MimeBodyPart();
			mb1.setContent("งามแสงเดือนมาเยือนส่องล้า งามใบหน้ามาสู่วงรำ", 
					"text/html;charset=UTF-8;");
			
			MimeBodyPart mbFile = new MimeBodyPart();
//			mbFile.attachFile(new File("D:\\NonMFEC\\Pu\\verisette\\NCOS\\APP2\\RESOURCES\\PDF\\DefaultNameCard.pdf"));
			StringBuilder path = new StringBuilder(ProjectConstant.BASE_APP_FOLDER);
			path.append("\\RESOURCES\\PDF\\");
			path.append("DefaultNameCard.pdf");
			mbFile.attachFile(new File(path.toString()));
			
			Multipart mp = new MimeMultipart();
			mp.addBodyPart(mb1);
//			mp.addBodyPart(mbFile);
			
//			message.setContent("Hey, It's just a test.", 
//					"text/html;charset=UTF-8;");
			
			message.setContent(mp);
			
			Transport.send(message);
			
			System.out.println("Done!!");
			
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}
